<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档处理 - RDK X5智能办公系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            padding-top: 56px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            background-color: #f8f9fa;
        }
        .content {
            flex: 1;
            padding: 2rem 0;
        }
        .footer {
            background-color: #343a40;
            color: #fff;
            padding: 1.5rem 0;
            margin-top: auto;
        }
        .process-card {
            margin-bottom: 1.5rem;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            border-radius: 0.5rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
            overflow: hidden;
        }
        .process-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15);
        }
        .process-card .card-header {
            background-color: #0d6efd;
            color: white;
            font-weight: 600;
            padding: 1rem;
        }
        .process-card .card-body {
            padding: 1.5rem;
        }
        .file-selector {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            margin-top: 1rem;
        }
        .progress {
            height: 1rem;
            border-radius: 0.5rem;
        }
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            color: white;
            flex-direction: column;
        }
        #progressLog {
            height: 200px;
            overflow-y: auto;
            font-family: "Courier New", monospace;
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            padding: 0.5rem;
            font-size: 0.875rem;
        }
        .task-list {
            max-height: 400px;
            overflow-y: auto;
        }
        /* 为PDF处理卡片添加特殊样式 */
        .row:first-of-type .process-card {
            border-left: 4px solid #0d6efd;
            transition: all 0.3s;
        }
        
        .row:first-of-type .process-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15);
        }
        
        /* 步骤标题样式 */
        h4 .bi-1-circle-fill, h4 .bi-2-circle-fill {
            color: #0d6efd;
        }
        
        /* 进度条和日志区域改进 */
        #progressLog {
            font-family: 'Courier New', monospace;
            line-height: 1.5;
            padding: 0.75rem;
            border-radius: 0.25rem;
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
        <div class="container">
            <a class="navbar-brand" href="/">RDK X5智能办公系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/">文档上传</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/process">文档处理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/download">文件下载</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 内容区 -->
    <div class="container content">
        <div class="row">
            <div class="col-12">
                <h1 class="display-5 mb-4">文档处理中心</h1>
                <p class="lead mb-4">为您的文档选择处理方式，支持PDF转换、文档总结、分点提炼和翻译。</p>
                
                <!-- 第一步：PDF处理卡片（单独一行） -->
                <div class="row mb-4">
                    <div class="col-12">
                        <h4 class="mb-3"><i class="bi bi-1-circle-fill me-2"></i>第一步：PDF文档转换</h4>
                        <div class="card process-card" data-bs-toggle="modal" data-bs-target="#pdfProcessModal">
                            <div class="card-header">
                                <i class="bi bi-file-pdf me-2"></i>PDF处理
                            </div>
                            <div class="card-body d-flex">
                                <div class="me-auto">
                                    <p>将PDF文档转换为结构化的Markdown格式，保留原文档的布局和图片。</p>
                                    <small class="text-muted">支持格式: PDF</small>
                                </div>
                                <div class="align-self-center ms-3">
                                    <i class="bi bi-arrow-right-circle fs-1 text-primary"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 第二步：后续处理功能（三个卡片一行） -->
                <div class="row">
                    <div class="col-12">
                        <h4 class="mb-3"><i class="bi bi-2-circle-fill me-2"></i>第二步：内容智能处理</h4>
                    </div>
                    
                    <!-- 文档总结卡片 -->
                    <div class="col-md-4 mb-4">
                        <div class="card process-card h-100" data-bs-toggle="modal" data-bs-target="#summaryModal">
                            <div class="card-header">
                                <i class="bi bi-journal-text me-2"></i>文档总结
                            </div>
                            <div class="card-body">
                                <p>使用AI快速总结文档内容，提取关键信息和主要观点。</p>
                                <small class="text-muted">支持格式: Markdown</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 分点提炼卡片 -->
                    <div class="col-md-4 mb-4">
                        <div class="card process-card h-100" data-bs-toggle="modal" data-bs-target="#extractionModal">
                            <div class="card-header">
                                <i class="bi bi-list-check me-2"></i>分点提炼
                            </div>
                            <div class="card-body">
                                <p>结构化提取文档要点，按层级归纳主题、观点和证据。</p>
                                <small class="text-muted">支持格式: Markdown</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 文档翻译卡片 -->
                    <div class="col-md-4 mb-4">
                        <div class="card process-card h-100" data-bs-toggle="modal" data-bs-target="#translationModal">
                            <div class="card-header">
                                <i class="bi bi-translate me-2"></i>文档翻译
                            </div>
                            <div class="card-body">
                                <p>智能翻译文档内容，支持中英双向互译，保留原文格式。</p>
                                <small class="text-muted">支持格式: Markdown</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 活动任务卡片 -->
                <div class="card mt-4">
                    <div class="card-header d-flex justify-content-between align-items-center bg-light">
                        <h5 class="mb-0">活动任务</h5>
                        <button id="refreshTasksBtn" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-arrow-clockwise"></i> 刷新
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div id="taskList" class="task-list list-group list-group-flush">
                            <div class="text-center p-3">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- PDF处理模态框 -->
    <div class="modal fade" id="pdfProcessModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-file-pdf me-2"></i>PDF处理</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>选择要处理的PDF文件:</p>
                    <div class="file-selector list-group" id="pdfFileList">
                        <div class="text-center p-3">加载中...</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="startPdfProcessBtn" disabled>开始处理</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 文档总结模态框 -->
    <div class="modal fade" id="summaryModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-journal-text me-2"></i>文档总结</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>选择要总结的Markdown文件:</p>
                    <div class="file-selector list-group" id="summaryFileList">
                        <div class="text-center p-3">加载中...</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="startSummaryBtn" disabled>开始处理</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 分点提炼模态框 -->
    <div class="modal fade" id="extractionModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-list-check me-2"></i>分点提炼</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>选择要提炼的Markdown文件:</p>
                    <div class="file-selector list-group" id="extractionFileList">
                        <div class="text-center p-3">加载中...</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="startExtractionBtn" disabled>开始处理</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 文档翻译模态框 -->
    <div class="modal fade" id="translationModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-translate me-2"></i>文档翻译</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>选择要翻译的Markdown文件:</p>
                    <div class="file-selector list-group" id="translationFileList">
                        <div class="text-center p-3">加载中...</div>
                    </div>
                    
                    <div class="mt-3">
                        <p>选择翻译方向:</p>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="translationDirection" id="directionZhToEn" value="1" checked>
                            <label class="form-check-label" for="directionZhToEn">
                                中文 → 英文
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="translationDirection" id="directionEnToZh" value="2">
                            <label class="form-check-label" for="directionEnToZh">
                                英文 → 中文
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="startTranslationBtn" disabled>开始处理</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 进度模态框 -->
    <div class="modal fade" id="progressModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="progressTitle">处理中</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="progress mb-3">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                    </div>
                    <p id="progressText" class="text-center">正在初始化处理任务...</p>
                    <div class="mt-3">
                        <h6>处理日志:</h6>
                        <pre id="progressLog" class="bg-light p-2 border rounded" style="height: 200px; overflow-y: auto;"></pre>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="cancelProcessBtn">
                        <i class="bi bi-x-circle me-1"></i> 取消处理
                    </button>
                    <button type="button" class="btn btn-primary" id="closeProgressBtn" data-bs-dismiss="modal" disabled>
                        <i class="bi bi-check-circle me-1"></i> 关闭
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载遮罩 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="spinner-border text-light mb-3" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <h4 id="loadingText">加载中，请稍候...</h4>
    </div>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="text-center">
                <p class="mb-0">RDK X5智能办公系统 &copy; 2025</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // DOM元素
            const loadingOverlay = document.getElementById('loadingOverlay');
            const loadingText = document.getElementById('loadingText');
            const pdfFileList = document.getElementById('pdfFileList');
            const summaryFileList = document.getElementById('summaryFileList');
            const extractionFileList = document.getElementById('extractionFileList');
            const translationFileList = document.getElementById('translationFileList');
            const startPdfProcessBtn = document.getElementById('startPdfProcessBtn');
            const startSummaryBtn = document.getElementById('startSummaryBtn');
            const startExtractionBtn = document.getElementById('startExtractionBtn');
            const startTranslationBtn = document.getElementById('startTranslationBtn');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            const progressLog = document.getElementById('progressLog');
            const progressTitle = document.getElementById('progressTitle');
            const cancelProcessBtn = document.getElementById('cancelProcessBtn');
            const closeProgressBtn = document.getElementById('closeProgressBtn');
            const taskList = document.getElementById('taskList');
            const refreshTasksBtn = document.getElementById('refreshTasksBtn');
            
            // 模态框对象
            const progressModal = new bootstrap.Modal(document.getElementById('progressModal'));
            
            // 当前选中的文件和进程ID
            let selectedPdfFile = null;
            let selectedMarkdownFile = null;
            let currentProcessId = null;
            let progressInterval = null;
            let lastLogContent = '';
            
            // 加载PDF文件列表
            function loadPdfFiles() {
                pdfFileList.innerHTML = '<div class="text-center p-3">加载中...</div>';
                fetch('/api/files')
                .then(response => response.json())
                .then(data => {
                    if (data.uploads && data.uploads.length > 0) {
                        // 过滤掉已被处理过的PDF（即output目录下已存在同名md文件的PDF）
                        fetch('/api/output')
                        .then(response => response.json())
                        .then(outputData => {
                            const processedPdfNames = new Set();
                            for (const folder in outputData) {
                                outputData[folder].forEach(file => {
                                    if (file.name.toLowerCase().endsWith('.md')) {
                                        processedPdfNames.add(file.name.replace(/\.md$/i, '.pdf'));
                                    }
                                });
                            }
                            const pdfFiles = data.uploads.filter(file => file.name.toLowerCase().endsWith('.pdf') && !processedPdfNames.has(file.name));
                            if (pdfFiles.length > 0) {
                                pdfFileList.innerHTML = '';
                                pdfFiles.forEach(file => {
                                    const item = document.createElement('button');
                                    item.className = 'list-group-item list-group-item-action d-flex align-items-center';
                                    item.innerHTML = `
                                        <i class="bi bi-file-pdf fs-4 me-2 text-danger"></i>
                                        <div>
                                            <h6 class="mb-0">${file.name}</h6>
                                            <small class="text-muted">${formatFileSize(file.size)} • ${file.modified}</small>
                                        </div>
                                    `;
                                    item.addEventListener('click', function() {
                                        pdfFileList.querySelectorAll('.list-group-item').forEach(el => {
                                            el.classList.remove('active');
                                        });
                                        this.classList.add('active');
                                        selectedPdfFile = file.name;
                                        startPdfProcessBtn.disabled = false;
                                    });
                                    pdfFileList.appendChild(item);
                                });
                            } else {
                                pdfFileList.innerHTML = '<div class="text-center p-3">没有可处理的PDF文件</div>';
                            }
                        });
                    } else {
                        pdfFileList.innerHTML = '<div class="text-center p-3">没有上传的文件</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    pdfFileList.innerHTML = '<div class="text-center p-3 text-danger">加载失败</div>';
                });
            }
            
            // 加载Markdown文件列表
            function loadMarkdownFiles() {
                summaryFileList.innerHTML = '<div class="text-center p-3">加载中...</div>';
                extractionFileList.innerHTML = '<div class="text-center p-3">加载中...</div>';
                translationFileList.innerHTML = '<div class="text-center p-3">加载中...</div>';
                
                fetch('/api/output')
                .then(response => response.json())
                .then(data => {
                    const markdownFiles = [];
                    
                    // 收集所有Markdown文件
                    for (const folder in data) {
                        data[folder].forEach(file => {
                            if (file.name.toLowerCase().endsWith('.md')) {
                                markdownFiles.push({
                                    name: file.name,
                                    size: file.size,
                                    modified: file.modified,
                                    folder: folder,
                                    path: folder + '/' + file.name  // 重要：构建完整的路径
                                });
                            }
                        });
                    }
                    
                    // 更新各个列表
                    if (markdownFiles.length > 0) {
                        updateMarkdownList(summaryFileList, markdownFiles, startSummaryBtn);
                        updateMarkdownList(extractionFileList, markdownFiles, startExtractionBtn);
                        updateMarkdownList(translationFileList, markdownFiles, startTranslationBtn);
                    } else {
                        const noFilesMessage = '<div class="text-center p-3">没有可用的Markdown文件</div>';
                        summaryFileList.innerHTML = noFilesMessage;
                        extractionFileList.innerHTML = noFilesMessage;
                        translationFileList.innerHTML = noFilesMessage;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    const errorMessage = '<div class="text-center p-3 text-danger">加载失败</div>';
                    summaryFileList.innerHTML = errorMessage;
                    extractionFileList.innerHTML = errorMessage;
                    translationFileList.innerHTML = errorMessage;
                });
            }
            
            // 更新Markdown文件列表
            function updateMarkdownList(container, files, startButton) {
                container.innerHTML = '';
                        
                files.forEach(file => {
                    const item = document.createElement('button');
                    item.className = 'list-group-item list-group-item-action d-flex align-items-center';
                    item.innerHTML = `
                        <i class="bi bi-file-text me-2 text-primary"></i>
                        <div class="flex-grow-1">
                            <div class="fw-semibold">${file.name}</div>
                            <small class="text-muted">${formatFileSize(file.size)} • ${file.modified}</small>
                        </div>
                    `;
                    
                    item.addEventListener('click', function() {
                        // 移除其他选中项的激活状态
                        container.querySelectorAll('.active').forEach(el => el.classList.remove('active'));
                        // 添加当前项的激活状态
                        this.classList.add('active');
                        // 保存选中的文件路径 (folder/filename)
                        selectedMarkdownFile = file.folder + '/' + file.name;
                        console.log("选中文件:", selectedMarkdownFile);
                        // 启用开始按钮
                        startButton.disabled = false;
                    });
                
                    container.appendChild(item);
                });
            }
            
            // 启动PDF处理
            startPdfProcessBtn.addEventListener('click', function() {
                if (!selectedPdfFile) return;
                
                // 显示进度模态框
                progressTitle.textContent = 'PDF处理中';
                progressBar.style.width = '0%';
                progressBar.textContent = '0%';
                progressText.textContent = '正在初始化处理任务...';
                progressLog.innerHTML = '';
                closeProgressBtn.disabled = true;
                progressModal.show();
                
                // 发送处理请求
                fetch('/api/process', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        filename: selectedPdfFile
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentProcessId = data.process_id;
                        startProgressUpdater();
                    } else {
                        progressText.textContent = '启动处理任务失败: ' + (data.error || '未知错误');
                        closeProgressBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    progressText.textContent = '启动处理任务时发生错误';
                    closeProgressBtn.disabled = false;
                });
            });
            
            // 启动文档总结
            startSummaryBtn.addEventListener('click', function() {
                if (!selectedMarkdownFile) return;
                
                // 显示进度模态框
                progressTitle.textContent = '文档总结中';
                progressBar.style.width = '0%';
                progressBar.textContent = '0%';
                progressText.textContent = '正在初始化处理任务...';
                progressLog.innerHTML = '';
                closeProgressBtn.disabled = true;
                progressModal.show();
                
                // 添加调试日志
                addToLog(`开始处理文件: ${selectedMarkdownFile}`);
                
                // 发送处理请求
                fetch('/api/llm', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        md_file: selectedMarkdownFile,  // 添加缺少的md_file参数
                        mode: 'summary'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentProcessId = data.process_id;  // 保存进程ID
                        addToLog(`处理任务已启动，进程ID: ${data.process_id}`);
                        startProgressUpdater();
                    } else {
                        progressText.textContent = data.error || '启动任务失败';
                        addToLog(`启动任务失败: ${data.error || '未知错误'}`);
                        closeProgressBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    progressText.textContent = '启动处理任务时发生错误';
                    addToLog(`请求错误: ${error.message || '网络请求失败'}`);
                    closeProgressBtn.disabled = false;
                });
            });

            // 启动分点提炼
            startExtractionBtn.addEventListener('click', function() {
                if (!selectedMarkdownFile) return;
                
                // 显示进度模态框
                progressTitle.textContent = '分点提炼中';
                progressBar.style.width = '0%';
                progressBar.textContent = '0%';
                progressText.textContent = '正在初始化处理任务...';
                progressLog.innerHTML = '';
                closeProgressBtn.disabled = true;
                progressModal.show();
                
                // 添加调试日志
                addToLog(`开始处理文件: ${selectedMarkdownFile}`);
                
                // 发送处理请求
                fetch('/api/llm', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        md_file: selectedMarkdownFile,  // 添加缺少的md_file参数
                        mode: 'extraction'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentProcessId = data.process_id;  // 保存进程ID
                        addToLog(`处理任务已启动，进程ID: ${data.process_id}`);
                        startProgressUpdater();
                    } else {
                        progressText.textContent = data.error || '启动任务失败';
                        addToLog(`启动任务失败: ${data.error || '未知错误'}`);
                        closeProgressBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    progressText.textContent = '启动处理任务时发生错误';
                    addToLog(`请求错误: ${error.message || '网络请求失败'}`);
                    closeProgressBtn.disabled = false;
                });
            });

            // 启动文档翻译
            startTranslationBtn.addEventListener('click', function() {
                if (!selectedMarkdownFile) return;
                
                // 获取翻译方向
                const translationDirection = document.querySelector('input[name="translationDirection"]:checked').value;
                
                // 显示进度模态框
                progressTitle.textContent = '文档翻译中';
                progressBar.style.width = '0%';
                progressBar.textContent = '0%';
                progressText.textContent = '正在初始化处理任务...';
                progressLog.innerHTML = '';
                closeProgressBtn.disabled = true;
                progressModal.show();
                
                // 添加调试日志
                addToLog(`开始处理文件: ${selectedMarkdownFile}`);
                addToLog(`翻译方向: ${translationDirection === '1' ? '中译英' : '英译中'}`);
                
                // 发送处理请求
                fetch('/api/llm', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        md_file: selectedMarkdownFile,  // 添加缺少的md_file参数
                        mode: 'translation',
                        translation_direction: translationDirection
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentProcessId = data.process_id;  // 保存进程ID
                        addToLog(`处理任务已启动，进程ID: ${data.process_id}`);
                        startProgressUpdater();
                    } else {
                        progressText.textContent = data.error || '启动任务失败';
                        addToLog(`启动任务失败: ${data.error || '未知错误'}`);
                        closeProgressBtn.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    progressText.textContent = '启动处理任务时发生错误';
                    addToLog(`请求错误: ${error.message || '网络请求失败'}`);
                    closeProgressBtn.disabled = false;
                });
            });
            
            // 启动进度更新
            function startProgressUpdater() {
                if (progressInterval) {
                    clearInterval(progressInterval);
                }
                
                // 立即执行一次更新
                updateProgress();
                updateLog();
                
                progressInterval = setInterval(() => {
                    updateProgress();
                    updateLog();
                }, 1000);
            }
            
            // 更新进度
            function updateProgress() {
                if (!currentProcessId) {
                    addToLog("警告: 找不到进程ID，无法更新进度");
                    return;
                }
                
                fetch(`/api/process/${currentProcessId}`)
                .then(response => response.json())
                .then(data => {
                    // 更新进度条
                    const progress = data.progress || 0;
                    progressBar.style.width = `${progress}%`;
                    progressBar.textContent = `${progress}%`;
                
                    // 更新状态文本
                    if (data.status === 'completed') {
                        progressText.textContent = '处理完成！';
                        closeProgressBtn.disabled = false;
                        clearInterval(progressInterval);
                        progressBar.classList.remove('progress-bar-animated');
                        // 添加完成的日志信息
                        addToLog('<span class="text-success"><b>✓ 处理成功完成！</b></span>');
                    } else if (data.status === 'failed') {
                        progressText.textContent = '处理失败！';
                        closeProgressBtn.disabled = false;
                        clearInterval(progressInterval);
                        progressBar.classList.remove('progress-bar-animated');
                        // 添加失败的日志信息
                        addToLog('<span class="text-danger"><b>✗ 处理失败！</b></span>');
                    } else {
                        progressText.textContent = `处理中... ${progress}%`;
                    }
                    
                    // 更新日志输出
                    if (data.output && data.output.length > 0) {
                        // 获取已显示的日志行数
                        const shownLogLines = progressLog.getElementsByTagName('div').length;
                        
                        // 显示新的日志内容
                        for (let i = 0; i < data.output.length; i++) {
                            const line = data.output[i].trim();
                            if (line && !progressLog.textContent.includes(line)) {
                                addToLog(line);
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    addToLog('<span class="text-warning">获取进度信息失败</span>');
                });
            }

            function updateLog() {
                if (!currentProcessId) return;
                fetch(`/api/process/${currentProcessId}/log`)
                    .then(response => response.json())
                    .then(data => {
                        if (typeof data.log === 'string' && data.log !== lastLogContent) {
                            progressLog.textContent = data.log;
                            lastLogContent = data.log;
                            progressLog.scrollTop = progressLog.scrollHeight;
                        }
                    });
            }
            
            // 取消处理
            cancelProcessBtn.addEventListener('click', function() {
                if (!currentProcessId) return;
                
                if (confirm('确定要取消当前处理任务吗？')) {
                    fetch(`/api/process/${currentProcessId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            progressText.textContent = '处理已中止';
                            closeProgressBtn.disabled = false;
                            clearInterval(progressInterval);
                        } else {
                            alert('取消处理失败: ' + (data.error || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('取消处理请求失败');
                    });
                }
            });
            
            // 关闭进度模态框
            document.getElementById('progressModal').addEventListener('hidden.bs.modal', function () {
                if (progressInterval) {
                    clearInterval(progressInterval);
                }
                currentProcessId = null;
            });
            
            // 加载活动任务
            function loadTasks() {
                taskList.innerHTML = `<div class="text-center p-3">加载中...</div>`;

                // 获取进行中的任务
                fetch('/api/process')
                .then(response => response.json())
                .then(data => {
                    if (data.length > 0) {
                        taskList.innerHTML = '';

                        data.forEach(task => {
                            // 确定任务类型和对应的颜色/图标
                            let taskTypeInfo = getTaskTypeInfo(task.type || 'unknown');

                            // 确定状态标签样式
                            let statusBadge = '';
                            if (task.status === 'running') {
                                statusBadge = '<span class="badge bg-primary">进行中</span>';
                            } else if (task.status === 'completed') {
                                statusBadge = '<span class="badge bg-success">完成</span>';
                            } else if (task.status === 'failed') {
                                statusBadge = '<span class="badge bg-danger">失败</span>';
                            } else if (task.status === 'terminated') {
                                statusBadge = '<span class="badge bg-warning">已终止</span>';
                            }

                            // 创建任务列表项
                            const item = document.createElement('div');
                            item.className = 'list-group-item';
                            item.innerHTML = `
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-1">
                                            <i class="${taskTypeInfo.icon} me-2"></i>
                                            ${task.filename}
                                        </h6>
                                        <div>
                                            <span class="badge bg-${taskTypeInfo.color} me-2">${taskTypeInfo.label}</span>
                                            ${statusBadge}
                                            <small class="text-muted ms-2">${task.start_time}</small>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="progress" style="width: 100px; height: 10px;">
                                            <div class="progress-bar ${task.status === 'running' ? 'progress-bar-striped progress-bar-animated' : ''}" 
                                                 role="progressbar" 
                                                 style="width: ${task.progress}%;" 
                                                 aria-valuenow="${task.progress}" 
                                                 aria-valuemin="0" 
                                                 aria-valuemax="100"></div>
                                        </div>
                                    </div>
                                </div>
                            `;
                            
                            taskList.appendChild(item);
                        });
                    } else {
                        taskList.innerHTML = '<div class="text-center p-3">没有正在进行的任务</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    taskList.innerHTML = '<div class="text-center p-3 text-danger">加载任务列表失败</div>';
                });
            }

            // 获取任务类型信息（图标、标签、颜色）
            function getTaskTypeInfo(taskType) {
                switch(taskType) {
                    case 'pdf':
                        return {
                            icon: 'bi bi-file-pdf',
                            label: 'PDF处理',
                            color: 'danger'
                        };
                    case 'summary':
                        return {
                            icon: 'bi bi-journal-text',
                            label: '文档总结',
                            color: 'info'
                        };
                    case 'extraction':
                        return {
                            icon: 'bi bi-list-check',
                            label: '分点提炼',
                            color: 'success'
                        };
                    case 'translation':
                        return {
                            icon: 'bi bi-translate',
                            label: '文档翻译',
                            color: 'warning'
                        };
                    default:
                        return {
                            icon: 'bi bi-file-earmark',
                            label: '未知任务',
                            color: 'secondary'
                        };
                }
            }
            
            // 刷新任务按钮
            refreshTasksBtn.addEventListener('click', loadTasks);
            
            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // 添加日志条目的辅助函数
            function addToLog(message) {
                const now = new Date();
                const timestamp = now.toLocaleTimeString();
                const logEntry = document.createElement('div');
                logEntry.innerHTML = `<span class="text-muted">[${timestamp}]</span> ${message}`;
                progressLog.appendChild(logEntry);
                // 自动滚动到底部
                progressLog.scrollTop = progressLog.scrollHeight;
            }

            // 启动进度更新
            function startProgressUpdater() {
                if (progressInterval) {
                    clearInterval(progressInterval);
                }
                
                // 立即执行一次更新
                updateProgress();
                updateLog();
                
                progressInterval = setInterval(() => {
                    updateProgress();
                    updateLog();
                }, 1000);
            }

            // 更新进度
            function updateProgress() {
                if (!currentProcessId) {
                    addToLog("警告: 找不到进程ID，无法更新进度");
                    return;
                }
                
                fetch(`/api/process/${currentProcessId}`)
                .then(response => response.json())
                .then(data => {
                    // 更新进度条
                    const progress = data.progress || 0;
                    progressBar.style.width = `${progress}%`;
                    progressBar.textContent = `${progress}%`;
                
                    // 更新状态文本
                    if (data.status === 'completed') {
                        progressText.textContent = '处理完成！';
                        closeProgressBtn.disabled = false;
                        clearInterval(progressInterval);
                        progressBar.classList.remove('progress-bar-animated');
                        // 添加完成的日志信息
                        addToLog('<span class="text-success"><b>✓ 处理成功完成！</b></span>');
                    } else if (data.status === 'failed') {
                        progressText.textContent = '处理失败！';
                        closeProgressBtn.disabled = false;
                        clearInterval(progressInterval);
                        progressBar.classList.remove('progress-bar-animated');
                        // 添加失败的日志信息
                        addToLog('<span class="text-danger"><b>✗ 处理失败！</b></span>');
                    } else {
                        progressText.textContent = `处理中... ${progress}%`;
                    }
                    
                    // 更新日志输出
                    if (data.output && data.output.length > 0) {
                        // 获取已显示的日志行数
                        const shownLogLines = progressLog.getElementsByTagName('div').length;
                        
                        // 显示新的日志内容
                        for (let i = 0; i < data.output.length; i++) {
                            const line = data.output[i].trim();
                            if (line && !progressLog.textContent.includes(line)) {
                                addToLog(line);
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    addToLog('<span class="text-warning">获取进度信息失败</span>');
                });
            }

            function updateLog() {
                if (!currentProcessId) return;
                fetch(`/api/process/${currentProcessId}/log`)
                    .then(response => response.json())
                    .then(data => {
                        if (typeof data.log === 'string' && data.log !== lastLogContent) {
                            progressLog.textContent = data.log;
                            lastLogContent = data.log;
                            progressLog.scrollTop = progressLog.scrollHeight;
                        }
                    });
            }
            
            // 初始化
            loadPdfFiles();
            loadMarkdownFiles();
            loadTasks();
            
            // 监听模态框显示事件，刷新列表
            document.querySelectorAll('.modal').forEach(modal => {
                modal.addEventListener('show.bs.modal', function() {
                    if (this.id === 'pdfProcessModal') {
                        loadPdfFiles();
                    } else if (['summaryModal', 'extractionModal', 'translationModal'].includes(this.id)) {
                        loadMarkdownFiles();
                    }
                });
            });
        });
    </script>
</body>
</html>